/**
 * @file  messagedispatcher.c                                                
 * @brief                                                     
 *                                                
 * 消息调度器    
 *
 * @author   caopx                                         
 * @version  1.00
 * @date     2025.9.12
 *
 */

#include "messagedispatcher.h"
#include "MessageQueue/inc/messagequeue.h"
#include "Log/inc/elog.h"

#include <sys/prctl.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>


static MessageQueue* pMessageDispatcherMQ = NULL;

void* dispatcherTask(void *pData);

/**
 * @brief 
 * 消息调度初始化  
 * @param
 * void
 * @return     
 * @retval	TRUE:success
 *			         FALSE:failure
 * @see       
 */
tel_bool_t dispatcherTaskInit(void)
{
    // 创建消息队列，容量为100
    pMessageDispatcherMQ = mq_init(100);
    if (!pMessageDispatcherMQ) {
        fprintf(stderr, "Failed to initialize message queue\n");
        return TEL_FALSE;
    }

    pthread_t dspatcher_thread;
    if (pthread_create(&dspatcher_thread, NULL, dispatcherTask, pMessageDispatcherMQ) != 0) {
        log_e("Failed to create dispatcherTask thread ");
        pthread_cancel(dspatcher_thread);
        return TEL_FALSE;
    }

    // 等待线程结束
    pthread_detach(dspatcher_thread);

    return TEL_TRUE;
}

/**
 * @brief 
 * 消息调度添加一个消息
 * @param
 * void
 * @return     
 * @see       
 */
void dispatcherApendMessage(tSysMsg* pMsg) {
    char buffer[256] = { 0 }; 
	memcpy(buffer, (char*)pMsg, sizeof(tSysMsg));
	mq_enqueue(pMessageDispatcherMQ,  buffer);
	usleep(10); 
}

/**
 * @brief 
 * 消息调度任务
 * @param  pData     
 * @return NULL     
 * @retval 
 * @see       
 */
void* dispatcherTask(void *pData)
{
    prctl(PR_SET_NAME, "dispatcher");
    MessageQueue* mq = (MessageQueue*)pData;
    tSysMsg buffer;
    
    while (1) {
        Message* msg = mq_dequeue(mq);
		 memcpy((char*)&buffer, msg->content, sizeof(tSysMsg));
        log_v("%s", buffer.msgBody );
        if (msg) {
            free(msg);
        }
        usleep(10); 
    }
    
    return NULL;

}




















